<template>
	<div class="academic-achievements">
		<div class="page-header">
			<h1 class="page-title">学术成果申报</h1>
			<div class="header-actions">
				<el-button type="success" @click="exportData">
					<el-icon><Download /></el-icon>
					导出数据
				</el-button>
				<el-button type="primary" @click="openFormDialog()">新增学术成果</el-button>
			</div>
		</div>

		<el-card>
			<div class="filter-bar">
				<el-input v-model="searchKeyword" placeholder="搜索论文标题或关键词" style="width: 200px;" :prefix-icon="Search" clearable @input="handleFilterChange" />
				<el-select v-model="filterType" placeholder="论文类型" style="width: 120px;" clearable @change="handleFilterChange">
					<el-option label="全部" value="" />
					<el-option label="期刊论文" value="期刊论文" />
					<el-option label="会议论文" value="会议论文" />
					<el-option label="书评" value="书评" />
					<el-option label="报刊理论文章" value="报刊理论文章" />
				</el-select>
				<el-select v-model="filterLanguage" placeholder="发表语言" style="width: 100px;" clearable @change="handleFilterChange">
					<el-option label="全部" value="" />
					<el-option label="中文" value="中文" />
					<el-option label="英文" value="英文" />
				</el-select>
				<el-select v-model="filterStatus" placeholder="审核状态" style="width: 120px;" clearable @change="handleFilterChange">
					<el-option label="全部" value="" />
					<el-option label="待审核" value="PENDING" />
					<el-option label="已通过" value="APPROVED" />
					<el-option label="已驳回" value="REJECTED" />
				</el-select>
				<el-date-picker v-model="filterYear" type="year" placeholder="发表年份" value-format="YYYY" style="width: 120px;" @change="handleFilterChange" />
			</div>

			<el-table :data="filteredAchievements" stripe v-loading="loading">
				<el-table-column prop="title" label="论文标题" min-width="300" show-overflow-tooltip />
				<el-table-column prop="type" label="论文类型" width="120">
					<template #default="{ row }">
						<el-tag :type="getTypeTagType(row.type)" size="small">
							{{ row.type }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="language" label="发表语言" width="80" />
				<el-table-column prop="journalConference" label="期刊/会议名称" min-width="200" show-overflow-tooltip />
				<el-table-column prop="publicationYear" label="发表年份" width="100" />
				<el-table-column prop="journalLevel" label="期刊级别/分区" width="120" show-overflow-tooltip />
				<el-table-column prop="status" label="审核状态" width="100">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createdAt" label="提交时间" width="160">
					<template #default="{ row }">
						{{ formatDateTime(row.createdAt) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150" fixed="right">
					<template #default="{ row }">
						<el-button type="primary" size="small" @click="viewAchievement(row)">查看</el-button>
						<el-button v-if="row.status === 'REJECTED'" type="warning" size="small" @click="editAchievement(row)">编辑</el-button>
						<el-button v-if="row.status === 'PENDING'" type="danger" size="small" @click="deleteAchievement(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 新增/编辑对话框 -->
		<el-dialog v-model="showFormDialog" :title="isEdit ? '编辑学术成果' : '新增学术成果'" width="1200px">
			<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="论文标题" prop="title">
							<el-input v-model="form.title" placeholder="请输入论文标题" />
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="论文类型" prop="type">
							<el-select v-model="form.type" placeholder="请选择论文类型" style="width: 100%;">
								<el-option label="期刊论文" value="期刊论文" />
								<el-option label="会议论文" value="会议论文" />
								<el-option label="书评" value="书评" />
								<el-option label="报刊理论文章" value="报刊理论文章" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="发表语言" prop="language">
							<el-select v-model="form.language" placeholder="请选择发表语言" style="width: 100%;">
								<el-option label="中文" value="中文" />
								<el-option label="英文" value="英文" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="发表年份" prop="publicationYear">
							<el-date-picker v-model="form.publicationYear" type="year" placeholder="选择年份" value-format="YYYY" style="width: 100%;" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="发表月份" prop="publicationMonth">
							<el-select v-model="form.publicationMonth" placeholder="选择月份" style="width: 100%;">
								<el-option v-for="month in 12" :key="month" :label="month + '月'" :value="month" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="期刊级别/分区" prop="journalLevel">
							<el-input v-model="form.journalLevel" placeholder="请输入期刊级别/分区" style="width: 100%;" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="会议级别" prop="conferenceLevel">
							<el-select v-model="form.conferenceLevel" placeholder="请选择会议级别" style="width: 100%;">
								<el-option label="国际顶级" value="国际顶级" />
								<el-option label="国际重要" value="国际重要" />
								<el-option label="国内重要" value="国内重要" />
								<el-option label="一般会议" value="一般会议" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item label="学科领域/关键词" prop="keywords">
					<el-input v-model="form.keywords" type="textarea" :rows="3" placeholder="请输入学科领域和关键词，用逗号分隔" />
				</el-form-item>

				<el-form-item label="发表期刊/会议名称" prop="journalConference">
					<el-input v-model="form.journalConference" placeholder="请输入发表期刊或会议名称" />
				</el-form-item>

				<el-form-item label="DOI号" prop="doi">
					<el-input v-model="form.doi" placeholder="请输入DOI号（可选）" />
				</el-form-item>

				<!-- 作者信息 -->
				<el-form-item label="作者信息">
					<div class="authors-section">
						<div v-for="(author, index) in form.authors" :key="index" class="author-item">
							<el-row :gutter="20">
								<el-col :span="3">
									<el-input v-model="author.authorName" placeholder="作者姓名" />
								</el-col>
								<el-col :span="3">
									<el-switch 
										v-model="author.isCurrentUnit" 
										active-text="本单位" 
										inactive-text="外单位"
										@change="(val) => handleUnitChange(index, val)"
									/>
								</el-col>
								<el-col :span="4">
									<el-input 
										v-model="author.authorUnit" 
										:placeholder="author.isCurrentUnit ? '北京电子科技学院' : '请输入单位名称'"
										:disabled="author.isCurrentUnit"
									/>
								</el-col>
								<el-col :span="3">
									<el-switch 
										v-model="author.isCurrentDepartment" 
										active-text="本系" 
										inactive-text="外系"
										:disabled="!author.isCurrentUnit"
										@change="(val) => handleDepartmentChange(index, val)"
									/>
								</el-col>
								<el-col :span="4">
									<el-select v-model="author.authorOrder" placeholder="署名顺序" style="width: 100%;">
										<el-option label="第一作者" value="第一作者" />
										<el-option label="通讯作者" value="通讯作者" />
										<el-option label="共同一作" value="共同一作" />
										<el-option label="第二作者" value="第二作者" />
										<el-option label="第三作者" value="第三作者" />
									</el-select>
								</el-col>
								<el-col :span="3">
									<el-input 
										v-model="author.staffNo" 
										:placeholder="author.isCurrentUnit ? '请输入工号' : '本单位才需填写'"
										:disabled="!author.isCurrentUnit"
									/>
								</el-col>
								<el-col :span="2">
									<el-button type="danger" size="small" @click="removeAuthor(index)" :disabled="form.authors.length === 1">删除</el-button>
								</el-col>
							</el-row>
						</div>
						<el-button type="primary" @click="addAuthor">添加作者</el-button>
					</div>
				</el-form-item>



				<el-form-item label="证明材料">
					<el-upload
						v-model:file-list="fileList"
						class="upload-demo"
						action="#"
						:auto-upload="false"
						accept=".jpg,.jpeg,.png,.pdf"
						:on-change="handleFileChange"
						:on-remove="handleFileRemove"
					>
						<el-icon class="el-icon--upload"><UploadFilled /></el-icon>
						<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
						<template #tip>
							<div class="el-upload__tip">仅支持 JPG/PNG/PDF，单个不超过 20MB，最多 5 个</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>

			<template #footer>
				<el-button @click="showFormDialog = false">取消</el-button>
				<el-button type="primary" :loading="submitting" @click="handleSubmit">提交</el-button>
			</template>
		</el-dialog>

		<!-- 查看对话框 -->
		<el-dialog v-model="showViewDialog" title="学术成果详情" width="800px">
			<el-descriptions :column="2" border>
				<el-descriptions-item label="论文标题">{{ viewData.title }}</el-descriptions-item>
				<el-descriptions-item label="论文类型">{{ viewData.type }}</el-descriptions-item>
				<el-descriptions-item label="发表语言">{{ viewData.language }}</el-descriptions-item>
				<el-descriptions-item label="发表年份">{{ viewData.publicationYear }}</el-descriptions-item>
				<el-descriptions-item label="发表月份">{{ viewData.publicationMonth }}</el-descriptions-item>
				<el-descriptions-item label="DOI号">{{ viewData.doi || '-' }}</el-descriptions-item>
				<el-descriptions-item label="期刊级别/分区">{{ viewData.journalLevel || '-' }}</el-descriptions-item>
				<el-descriptions-item label="会议级别">{{ viewData.conferenceLevel || '-' }}</el-descriptions-item>
				<el-descriptions-item label="学科领域/关键词" :span="2">{{ viewData.keywords || '-' }}</el-descriptions-item>
				<el-descriptions-item label="发表期刊/会议名称" :span="2">{{ viewData.journalConference || '-' }}</el-descriptions-item>
				<el-descriptions-item label="审核状态">
					<el-tag :type="getStatusType(viewData.status)">{{ getStatusText(viewData.status) }}</el-tag>
				</el-descriptions-item>
				<el-descriptions-item label="提交时间">{{ formatDateTime(viewData.createdAt) }}</el-descriptions-item>
				<el-descriptions-item v-if="viewData.reviewOpinion" label="审核意见" :span="2">{{ viewData.reviewOpinion }}</el-descriptions-item>
			</el-descriptions>

			<!-- 作者信息 -->
			<div v-if="viewData.authors && viewData.authors.length > 0" style="margin-top: 20px;">
				<h4>作者信息</h4>
				<el-table :data="viewData.authors" border>
					<el-table-column prop="authorName" label="作者姓名" />
					<el-table-column prop="authorUnit" label="作者单位" />
					<el-table-column prop="authorOrder" label="署名顺序" />
					<el-table-column prop="isCurrentUnit" label="是否本单位">
						<template #default="{ row }">
							<el-tag :type="row.isCurrentUnit ? 'success' : 'info'">
								{{ row.isCurrentUnit ? '是' : '否' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="staffNo" label="工号" />
				</el-table>
			</div>

			<!-- 附件信息 -->
			<div v-if="viewData.attachments && viewData.attachments.length > 0" style="margin-top: 20px;">
				<h4>证明材料</h4>
				<el-table :data="viewData.attachments" border>
					<el-table-column prop="fileName" label="文件名" />
					<el-table-column prop="fileType" label="文件类型" />
					<el-table-column prop="fileSize" label="文件大小">
						<template #default="{ row }">
							{{ formatFileSize(row.fileSize) }}
						</template>
					</el-table-column>
					<el-table-column label="操作">
						<template #default="{ row }">
							<el-button type="primary" size="small" @click="downloadFile(row)">下载</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, UploadFilled, Download } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
	createAcademicAchievement,
	createAcademicAchievementJson,
	getMyAcademicAchievements,
	updateAcademicAchievement,
	updateAcademicAchievementJson,
	deleteAcademicAchievement,
	getAcademicAchievement
} from '@/api/academicAchievement'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showFormDialog = ref(false)
const showViewDialog = ref(false)
const isEdit = ref(false)
const achievements = ref([])
const viewData = ref({})

// 筛选条件
const searchKeyword = ref('')
const filterType = ref('')
const filterLanguage = ref('')
const filterStatus = ref('')
const filterYear = ref('')

// 表单数据
const formRef = ref()
const form = reactive({
	title: '',
	type: '',
	language: '',
	keywords: '',
	journalConference: '',
	publicationYear: '',
	publicationMonth: '',
	doi: '',
	journalLevel: '',
	conferenceLevel: '',
	authors: [{ 
		authorName: '', 
		authorUnit: '', 
		authorOrder: '', 
		isCurrentUnit: false, 
		staffNo: '',
		isCurrentDepartment: false // 是否本系
	}]
})

// 本系作者（已删除，改为在作者信息中处理）

// 文件列表
const fileList = ref([])

// 表单验证规则
const rules = {
	title: [{ required: true, message: '请输入论文标题', trigger: 'blur' }],
	type: [{ required: true, message: '请选择论文类型', trigger: 'change' }],
	language: [{ required: true, message: '请选择发表语言', trigger: 'change' }],
	publicationYear: [{ required: true, message: '请选择发表年份', trigger: 'change' }],
	keywords: [{ required: true, message: '请输入学科领域/关键词', trigger: 'blur' }],
	journalConference: [{ required: true, message: '请输入发表期刊/会议名称', trigger: 'blur' }]
}

// 计算属性
const filteredAchievements = computed(() => {
	let result = achievements.value

	if (searchKeyword.value) {
		result = result.filter(item => 
			item.title.includes(searchKeyword.value) || 
			(item.keywords && item.keywords.includes(searchKeyword.value))
		)
	}

	if (filterType.value) {
		result = result.filter(item => item.type === filterType.value)
	}

	if (filterLanguage.value) {
		result = result.filter(item => item.language === filterLanguage.value)
	}

	if (filterStatus.value) {
		result = result.filter(item => item.status === filterStatus.value)
	}

	if (filterYear.value) {
		result = result.filter(item => item.publicationYear === parseInt(filterYear.value))
	}

	return result
})

// 方法
const fetchAchievements = async () => {
	try {
		loading.value = true
		const response = await getMyAcademicAchievements({ userId: userStore.userInfo?.id })
		achievements.value = Array.isArray(response) ? response : (response?.data || [])
	} catch (error) {
		console.error('获取学术成果列表失败:', error)
		ElMessage.error('获取学术成果列表失败')
	} finally {
		loading.value = false
	}
}

const openFormDialog = (achievement = null) => {
	if (achievement) {
		isEdit.value = true
		// 复制数据但不包括状态相关字段
		Object.assign(form, {
			title: achievement.title,
			type: achievement.type,
			language: achievement.language,
			keywords: achievement.keywords,
			journalConference: achievement.journalConference,
			publicationYear: achievement.publicationYear,
			publicationMonth: achievement.publicationMonth,
			doi: achievement.doi,
			journalLevel: achievement.journalLevel,
			conferenceLevel: achievement.conferenceLevel,
			id: achievement.id
		})
		// 处理作者信息
		if (achievement.authors) {
			form.authors = achievement.authors.map(author => ({
				authorName: author.authorName,
				authorUnit: author.authorUnit,
				authorOrder: author.authorOrder,
				isCurrentUnit: author.isCurrentUnit,
				staffNo: author.staffNo,
				isCurrentDepartment: author.isCurrentDepartment || false
			}))
		}
	} else {
		isEdit.value = false
		resetForm()
	}
	showFormDialog.value = true
}

const resetForm = () => {
	Object.assign(form, {
		title: '',
		type: '',
		language: '',
		keywords: '',
		journalConference: '',
		publicationYear: '',
		publicationMonth: '',
		doi: '',
		journalLevel: '',
		conferenceLevel: '',
		authors: [{ 
			authorName: '', 
			authorUnit: '', 
			authorOrder: '', 
			isCurrentUnit: false, 
			staffNo: '',
			isCurrentDepartment: false
		}]
	})
	fileList.value = []
}

const addAuthor = () => {
	form.authors.push({ 
		authorName: '', 
		authorUnit: '', 
		authorOrder: '', 
		isCurrentUnit: false, 
		staffNo: '',
		isCurrentDepartment: false
	})
}

const removeAuthor = (index) => {
	if (form.authors.length > 1) {
		form.authors.splice(index, 1)
	}
}

// 处理本单位/外单位选择
const handleUnitChange = (index, isCurrentUnit) => {
	if (isCurrentUnit) {
		form.authors[index].authorUnit = '北京电子科技学院'
		form.authors[index].isCurrentDepartment = false // 重置本系状态
	} else {
		form.authors[index].authorUnit = ''
		form.authors[index].isCurrentDepartment = false
	}
}

// 处理本系选择
const handleDepartmentChange = (index, isCurrentDepartment) => {
	form.authors[index].isCurrentDepartment = isCurrentDepartment
}

const handleFileChange = (file) => {
	// 文件大小限制
	if (file.size > 20 * 1024 * 1024) {
		ElMessage.error('文件大小不能超过20MB')
		return false
	}
}

const handleFileRemove = (file) => {
	const index = fileList.value.findIndex(f => f.uid === file.uid)
	if (index > -1) {
		fileList.value.splice(index, 1)
	}
}

const handleSubmit = async () => {
	try {
		await formRef.value.validate()
		submitting.value = true

		const submitData = {
			...form,
			createdBy: userStore.userInfo?.id // 设置创建者ID
		}

		if (isEdit.value) {
			// 编辑时使用JSON格式的API，避免multipart错误
			await updateAcademicAchievementJson(form.id, submitData)
			ElMessage.success('更新成功，已重新提交审核')
		} else {
			// 新增时使用JSON格式的API，避免multipart错误
			await createAcademicAchievementJson(submitData)
			ElMessage.success('提交成功，等待审核')
		}

		showFormDialog.value = false
		fetchAchievements()
	} catch (error) {
		console.error('提交失败:', error)
		ElMessage.error('提交失败')
	} finally {
		submitting.value = false
	}
}

const viewAchievement = async (row) => {
	try {
		const response = await getAcademicAchievement(row.id)
		viewData.value = response.achievement || response
		showViewDialog.value = true
	} catch (error) {
		console.error('获取详情失败:', error)
		ElMessage.error('获取详情失败')
	}
}

const editAchievement = (row) => {
	openFormDialog(row)
}

const deleteAchievement = async (row) => {
	try {
		await ElMessageBox.confirm('确定要删除这个学术成果吗？', '确认删除', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		})

		await deleteAcademicAchievement(row.id)
		ElMessage.success('删除成功')
		fetchAchievements()
	} catch (error) {
		if (error !== 'cancel') {
			console.error('删除失败:', error)
			ElMessage.error('删除失败')
		}
	}
}

const handleFilterChange = () => {
	// 实时筛选，无需额外处理
}

const getTypeTagType = (type) => {
	const types = {
		'期刊论文': 'primary',
		'会议论文': 'success',
		'书评': 'warning',
		'报刊理论文章': 'info'
	}
	return types[type] || 'info'
}

const getStatusType = (status) => {
	const types = {
		'PENDING': 'info',
		'APPROVED': 'success',
		'REJECTED': 'danger'
	}
	return types[status] || 'info'
}

const getStatusText = (status) => {
	const texts = {
		'PENDING': '待审核',
		'APPROVED': '已通过',
		'REJECTED': '已驳回'
	}
	return texts[status] || status
}

const formatDateTime = (date) => {
	if (!date) return '-'
	try {
		return new Date(date).toLocaleString('zh-CN')
	} catch {
		return '-'
	}
}

const formatFileSize = (size) => {
	if (!size) return '-'
	if (size < 1024) return size + ' B'
	if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
	return (size / (1024 * 1024)).toFixed(2) + ' MB'
}

const downloadFile = (file) => {
	// 实现文件下载逻辑
	ElMessage.info('文件下载功能待实现')
}

// 生命周期
// 导出数据
const exportData = async () => {
	const { exportData: exportUtil } = await import('@/utils/exportUtils')
	
	const filters = {
		search: searchKeyword.value,
		type: filterType.value,
		status: filterStatus.value
	}
	
	await exportUtil('academic-achievements', filters, '学术成果列表.xlsx')
}

onMounted(() => {
	fetchAchievements()
})
</script>

<style scoped>
.academic-achievements {
	max-width: 1400px;
}

/* 作者信息表格优化 */
.authors-section .author-item {
	margin-bottom: 20px;
	padding: 20px;
}

.authors-section .author-item .el-row {
	align-items: center;
}

.authors-section .author-item .el-col {
	margin-bottom: 0;
}

/* 开关组件样式优化 */
.authors-section .el-switch {
	width: 100%;
}

.authors-section .el-switch .el-switch__label {
	font-size: 12px;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24px;
}

.page-title {
	margin: 0;
	color: #333;
	font-size: 24px;
	font-weight: 500;
}

.header-actions {
	display: flex;
	align-items: center;
}

.filter-bar {
	margin-bottom: 16px;
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	gap: 16px;
}

.authors-section {
	margin-bottom: 16px;
}

.author-item {
	margin-bottom: 16px;
	padding: 16px;
	border: 1px solid #e4e7ed;
	border-radius: 8px;
	background-color: #fafafa;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.author-item:hover {
	background-color: #f5f7fa;
	border-color: #c0c4cc;
}

.author-item .el-row {
	align-items: center;
}

.author-item .el-col {
	margin-bottom: 8px;
}

.upload-demo {
	width: 100%;
}

/* 响应式布局 */
@media (max-width: 1200px) {
	.author-item .el-col {
		margin-bottom: 12px;
	}
}

@media (max-width: 768px) {
	.author-item .el-row {
		flex-direction: column;
	}
	
	.author-item .el-col {
		width: 100% !important;
		margin-bottom: 12px;
	}
}
</style>
